#include <iostream>
#include <stdio.h>
#include <strings.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "Log.hpp"

volatile bool quitSer = false;

void Usage(void *vgs)
{
    std::cout << "Usage:./tcpserver port ip" << std::endl;
}
class server
{
public:
    server(int port, std::string ip = "")
        : sockfd_(-1), ip_(ip), port_(port)
    {
    }
    ~server()
    {
    }

public:
    void init()
    {
        // 1. 创建套接字
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            logMessage(FATAL, "socket:%s[%d]", strerror(errno), sockfd_);
            exit(SOCK_ERR);
        }
        logMessage(DEBUG, "socket success..");

        // 2.填充域
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        ip_.empty() ? (local.sin_addr.s_addr = INADDR_ANY) : (inet_aton(ip_.c_str(), &local.sin_addr));

        // 3. 绑定网络信息
        if (bind(sockfd_, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind:%s[%d]", strerror(errno), sockfd_);
            exit(BIND_ERR);
        }
        logMessage(DEBUG, "bind success...");

        // 4. 监听套接字
        if (listen(sockfd_, 5) < 0)
        {
            logMessage(FATAL, "listen:%s[%d]", strerror(errno), sockfd_);
            exit(LISTEN_ERR);
        }
        logMessage(DEBUG, "listen success...");

        // 完成
    }
    // void *sendMessage(void* vgs)
    // {
    //     pthread_detach(pthread_self());
    //     int sockfd = *(int*)vgs;

    //     while(true)
    //     {

    //     }
    // }

    void start()
    {
        char inbuffer_[1024]; // 用来接收客户端发来的消息
        // 提供服务
        while (true)
        {
            quitSer = false;

            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 5. 获取连接, accept 的返回值是一个新的socket fd
            int serviceSock = accept(sockfd_, (struct sockaddr *)&peer, &len);
            if (serviceSock < 0)
            {
                // 获取链接失败
                logMessage(WARINING, "accept: %s[%d]", strerror(errno), serviceSock);
                continue;
            }

            logMessage(DEBUG, "accept success");
            while (!quitSer)
            {
                memset(inbuffer_, 0, sizeof(inbuffer_));
                ssize_t s = recvfrom(serviceSock, inbuffer_, sizeof(inbuffer_) - 1, 0,
                                     (struct sockaddr *)&peer, &len);

                if (s > 0)
                {
                    std::cout << s << std::endl;
                    // 接收成功
                    inbuffer_[s] = '\0';
                }
                else if (s == -1)
                {
                    //
                    logMessage(WARINING, "recvfrom fialed:%s[%d]", strerror(errno), sockfd_);
                    continue;
                }
                uint16_t peerPort = ntohs(peer.sin_port);
                std::string peerIp = inet_ntoa(peer.sin_addr);
                if(s > 0)
                    logMessage(NOTICE, "[%s:%d]# %s", peerIp.c_str(), peerPort, inbuffer_);
                if (strcmp(inbuffer_, "quit") == 0)
                {
                    quitSer = true;
                    logMessage(DEBUG, "quit server...");
                }
                sendto(serviceSock, inbuffer_, strlen(inbuffer_), 0,\
                        (const struct sockaddr *)&peer, sizeof(peer)); 
            }
            //logMessage(DEBUG, "quit server...");
            close(serviceSock);
        }
    }

private:
    int sockfd_;
    uint16_t port_;
    std::string ip_;

};

// ./tcpserver port ip
int main(int argc, char *argv[])
{
    if (argc < 2 || argc > 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]);
    std::string ip;
    if (argc == 3)
        ip = argv[2];

    server tcpSer(port, ip);
    tcpSer.init();
    tcpSer.start();
    return 0;
}
